const config = require("../config.js");
const normalResult = require("../normalResult.js");

function responseMiddleware(request, response, next) {
    response.success = (params) => {
        // console.log(params)
        let r = JSON.parse(normalResult)
        r.data = params.data
        r.code = config.result.success.code;
        r.msg = params.msg ||  config.result.success.msg;
        r.total = params.total || 0
        response.status(r.code).json(r);
    };

    response.error = (params) => {
        let r = JSON.parse(normalResult)
        r.data = null;
        r.code = params.code || config.result.error.code;
        r.msg = params.msg || config.result.error.msg;
        delete r.total;
        response.status(r.code).json(r);
    };

    response.showResult = (params) => {
        let r = JSON.parse(normalResult)
        r.data = params.data
        r.msg = params.msg;
        r.code = params.code || config.result.error.code
        r.total = params.total || 0
        if (params.code !== config.result.success.code) delete r.total;
        response.status(r.code).json(r);
    }

    next();
}

exports.responseMiddleware = responseMiddleware;